export interface ApiResp<T> {
    code: number
    msg: string
    data: T

    isSuccess(): boolean
    isFail(): boolean
  }

  export class ApiResponse<T> implements ApiResp<T> {
    code: number
    msg: string
    data: T

    constructor(code: number, msg: string, data: T) {
      this.code = code
      this.msg = msg
      this.data = (data === null || data === undefined )
        ? (Array.isArray(data) ? [] : typeof data === 'object' ? {} : data) as T
        : data
    }

    isSuccess(): boolean {
      return this.code === 1
    }

    isFail(): boolean {
      return !this.isSuccess()
    }

    static convert<T>(data: unknown): ApiResponse<T> {
      if (typeof data === 'object' && data!== null && 'code' in data && 'msg' in data && 'data' in data) {
        const result = (data as ApiResponse<T>);
        if (result.data === undefined || data?.data === undefined) {
          result.data = (Array.isArray(data?.data) ? [] : typeof data?.data === 'object' ? {} : data?.data) as T
        }
        return result
      }
      throw new Error('参数格式错误，不是ApiResponse类型')
    }

  }


  export interface ApiPageReq {
    page: number
    size: number
  }
  export interface ApiPageResp<T> {
    page: number
    size: number
    total: number
    data: T
  }
